﻿using BG.Data;
using Kwan.Cache;
using Kwan.Data;

namespace BG.Service
{
    public class ConfigManager
    {
        private static string key = "SystemConfig";
        private TConfig config;
        private TUser user;
        protected CacheManage theCache;//缓存对象
        public ConfigManager()
        {
            theCache = CacheManage.Instance;
        }
        private class Shell
        {
            internal static readonly ConfigManager instance = new ConfigManager();
        }
        public static ConfigManager Instance
        {
            get { return Shell.instance; }
        }
        public TConfig LoadFromCache()
        {
            if (theCache.Contains(key))//缓存中存在对应值是key的对象
            {
                return theCache.Get(key) as TConfig;
            }
            else
            {
                config = new Expression().ListFirst<TConfig>();
                theCache.Add(key, config);
                return theCache.Get(key) as TConfig;
            }
        }
        public void SaveConfig(TConfig t)
        {
            DBContext.Save(t);
            theCache.Remove(key);
            config = new Expression().ListFirst<TConfig>();
            theCache.Add(key, config);
        }
        public TUser IndentityUser()
        {
            if (theCache.Contains("IndentityUser"))//缓存中存在对应值是key的对象
            {
                return theCache.Get("IndentityUser") as TUser;
            }
            else
            {
                user = (TUser.userName == System.Web.HttpContext.Current.User.Identity.Name).ListFirst<TUser>();
                theCache.Add("IndentityUser", user);
                return theCache.Get("IndentityUser") as TUser;
            }
        }

        #region IDisposable成员
        public void Dispose()
        {
            Dispose(true);
            //GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                lock (this)
                {
                    if (disposing)
                    {
                        config = null;
                        user = null;
                    }
                    m_disposed = true;
                }
            }
        }
        ~ConfigManager()
        {
            Dispose(false);
        }
        private bool m_disposed;
        #endregion
    }
}
